﻿using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using NHibernate;
using SportWebShop.App_Start;

namespace SportWebShop
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : System.Web.HttpApplication
	{
		private static IWindsorContainer windsorContainer;

		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default", // Route name
				"{controller}/{action}/{id}", // URL with parameters
				new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
			);

			routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

		}

		protected void Application_Start()
		{
			windsorContainer = Initialize();
			AreaRegistration.RegisterAllAreas();
			ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(windsorContainer.Kernel));

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
		}

		private IWindsorContainer Initialize()
		{
			windsorContainer = new WindsorContainer();
			windsorContainer.Register(Component.For<IWindsorContainer>().Instance(windsorContainer));
			NHibernateConfiguration.BuildSchema(true);
			windsorContainer.Register(Component.For<ISessionFactory>().Instance(NHibernateConfiguration.SessionFactory));
			windsorContainer.Register(Classes
				.FromAssembly(Assembly.GetExecutingAssembly())
				.BasedOn<IController>()
				.Configure(component => component.LifeStyle.Transient
				.Named(component.Implementation.ToString()))
			);
			return windsorContainer;
		}

		protected void Application_End()
		{
			if (windsorContainer != null)
			{
				windsorContainer.Dispose();
			}
		}
	}
}